//
//  UIStackView+zj.swift
//  ZJSwiftKit
//
//  Created by 左潇 on 2023/6/30.
//

import Foundation

public extension ZJPrefix where Base: UIStackView {
    
    
    /// 将视图数组添加到arrangedSubviews数组的末尾。
    ///
    /// - Parameter views: views array.
    func addArrangedSubviews(_ views: [UIView]) {
        for view in views {
            base.addArrangedSubview(view)
        }
    }
    
    /// 将视图数组从arrangedSubviews数组中移除
    func removeArrangedSubviews() {
        for view in base.arrangedSubviews {
            base.removeArrangedSubview(view)
        }
    }
    
    /// 交换已插入视图的两个视图。
    /// - Parameters:
    ///   - view1: 视图1
    ///   - view2: 视图2
    ///   - animated: 设置为true以动画交换(默认为true)。
    ///   - duration: animation duration in seconds (default is 1 second).
    ///   - delay: 动画持续时间以秒为单位(默认为1秒)。
    ///   - options: 动画选项(默认是AnimationOptions.curveLinear)。
    ///   - completion: 可选的完成处理程序回掉，在动画完成时运行(默认为nil)。
    func swap(_ view1: UIView, _ view2: UIView,
              animated: Bool = false,
              duration: TimeInterval = 0.25,
              delay: TimeInterval = 0,
              options: UIView.AnimationOptions = .curveLinear,
              completion: ((Bool) -> Void)? = nil) {
        func swapViews(_ view1: UIView, _ view2: UIView) {
            guard let view1Index = base.arrangedSubviews.firstIndex(of: view1),
                  let view2Index = base.arrangedSubviews.firstIndex(of: view2)
            else { return }
            base.removeArrangedSubview(view1)
            base.insertArrangedSubview(view1, at: view2Index)
            
            base.removeArrangedSubview(view2)
            base.insertArrangedSubview(view2, at: view1Index)
        }
        if animated {
            UIView.animate(withDuration: duration, delay: delay, options: options, animations: {
                swapViews(view1, view2)
                base.layoutIfNeeded()
            }, completion: completion)
        } else {
            swapViews(view1, view2)
        }
    }
}
